package Sales;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.Timer;
 
 
import java.awt.event.*;
import Inventory.GBPane;

import Expense.ExpensePane;
import Inventory.InventoryPane;
import Login.Button;
import Login.DBHandler;
import Login.MainFrame;
import User.UserPane;
import Inventory.GBPane;

public class SalePane extends JPanel implements FocusListener, KeyListener,
		ItemListener, ActionListener, MouseMotionListener, MouseListener {
	private DBHandler db;
	private JPanel parent, debtPane;
	private CardLayout cards;
	private BufferedImage bg, panel1, panel2, panel3, panel4;
	private JFrame frame;
	private int userType, curPanel;
	private String error;
	private Button salesBtn, inBtn, expBtn, usBtn, logBtn, viewSales, createIn,
			updIn, custBal;
	private JButton insert, reset, prevDay, prev, nextDay, next, delete;
	private JTextField soldToBox, inNumBox, customerName, totalBox, balanceBox;
	private Timer time;
	private JComboBox dayBox, yearBox, monthBox, invoiceBox;
	private Date date;
	private JLabel d, m, y;
	private JLabel soldTo, inNum, day, month, year, customer, total, balance,
			limit;
	private JPanel viewPane;
	private JScrollPane scrollPane, scrollPane2, scrollPane3;
	private ArrayList<Invoice> Invoices;
	private ArrayList<JTextField> quantityBoxes, unitBoxes, prodBoxes,
			priceBoxes, newQuans, newPrices;
	private ArrayList<JComboBox> addUnits, addProd;
	private Inventory.GBPane newSales;
	private JTextField enterQuan, enterPrice, limitBox;
	private JComboBox enterUnit, enterProd;
	private Invoice selected;

	public SalePane(DBHandler db, JPanel parent, CardLayout cards, BufferedImage bg, JFrame frame, int userType){
		this.db=db;
		this.parent=parent;
		this.cards=cards;
		this.bg=bg;
		this.frame=frame;
		this.userType=userType;
		this.setLayout(null);
		error="";	
		curPanel=0;
		showButtons();
		viewSales.setCurImg(1);
		error="";	
		date=new Date();
		
		Invoices=getDBItems("SELECT * from Invoice where dateofReceipt=CurDate();");
		viewPane=new JPanel();
		
		day = new JLabel("Day :");
		month = new JLabel("Month :");
		year = new JLabel("Year :");
		d=new JLabel((date.getDate())+"");
		customer = new JLabel("Customer Name:");
		total= new JLabel("Total:");
		balance = new JLabel("Balance:");
		soldTo =  new JLabel("Sold To:");
		inNum = new JLabel("Invoice No.: ");
		limit = new JLabel("Limit: ");
		
		soldTo.setVisible(false);
		inNum.setVisible(false);
		dayBox=new JComboBox();
		monthBox=new JComboBox();
		yearBox=new JComboBox();
		invoiceBox = new JComboBox();
		prevDay=new JButton("Previous Day");
		prev= new JButton("Previous");
		nextDay= new JButton("Next Day");
		next= new JButton("Next");
		soldToBox = new JTextField();
		inNumBox = new JTextField();
		reset=new JButton("Reset");
		insert = new JButton("Insert");
		limitBox = new JTextField("5000");
		delete = new JButton("Delete");
		try{
			setComboBoxItems(monthBox);
			setComboBoxItems(yearBox);
			addInvoicestoCombobox();
		} catch(SQLException SqlEx){}
		
		if(Invoices.size()>0){
            selected=Invoices.get(0);
            customerName=new JTextField(selected.getCustomerName());
        	totalBox=new JTextField(selected.getTotal()+"");
        	balanceBox=new JTextField(selected.getBalance()+"");
        	
		}
        else {
            customerName=new JTextField(5);
            totalBox=new JTextField(5);
            balanceBox=new JTextField(5);
        }

		recordPaneConfig(0,false);
		
		limitBox.addKeyListener(this);
		limitBox.addFocusListener(this);
		String s="";
		switch(date.getMonth()){
		case 0: s="January"; break;
		case 1: s="February"; break;
		case 2: s="March"; break;
		case 3: s="April"; break;
		case 4: s="May"; break;
		case 5: s="June"; break;
		case 6: s="July"; break;
		case 7: s="August"; break;
		case 8: s="September"; break;
		case 9: s="October"; break;
		case 10: s="November"; break;
		case 11: s="December"; break;
		}
		m=new JLabel(s);
		y=new JLabel((date.getYear()+1900)+"");
		
		dayBox.setBounds(280, 185, 45, dayBox.getPreferredSize().height);
		monthBox.setBounds(375, 185, 100, monthBox.getPreferredSize().height);
		yearBox.setBounds(523, 185, 70, yearBox.getPreferredSize().height);
		day.setBounds(248, 169, 50, 50);
		month.setBounds(335, 169, 70, 50);
		year.setBounds(475, 169, 70, 50);
		invoiceBox.setBounds(310, 225, 190, 26);
		d.setBounds(298, 187, 50, d.getPreferredSize().height);
		m.setBounds(385, 187, 100, m.getPreferredSize().height);
		y.setBounds(523, 187, 50, y.getPreferredSize().height);

		prevDay.setBounds(135, 180, prevDay.getPreferredSize().width,
				prevDay.getPreferredSize().height);
		prev.setBounds(205, 225, prev.getPreferredSize().width,
				prev.getPreferredSize().height);
		nextDay.setBounds(615, 180, nextDay.getPreferredSize().width,
				nextDay.getPreferredSize().height);
		next.setBounds(524, 225, next.getPreferredSize().width,
				next.getPreferredSize().height);
		customer.setBounds(143, 259, 100, 30);
		customerName.setBounds(250, 264, 180, customerName.getPreferredSize().height);
		total.setBounds(538, 431, 50, 20);
		balance.setBounds(538, 451, 70, 20);
		totalBox.setBounds(587, 429, 125, 20);
		balanceBox.setBounds(587, 451, 125, 20);
		soldTo.setBounds(146, 213, 50, 20);
		inNum.setBounds(454, 213, 70, 20);
		soldToBox.setBounds(192, 211, 200, soldToBox.getPreferredSize().height)	;
		inNumBox.setBounds(518, 211, 150, inNumBox.getPreferredSize().height);
		reset.setBounds(385, 437, 100, 30);
		insert.setBounds(161, 437, 100, 30);
		limit.setBounds(340, 215, 50, limit.getPreferredSize().height);
		limitBox.setBounds(380, 213, 125, limitBox.getPreferredSize().height);
		delete.setBounds(161, 437, 100, 30);
		
		Font font2 = new Font("Calibri", Font.PLAIN, 15); 
		dayBox.setFont(font2);
		monthBox.setFont(font2);
		yearBox.setFont(font2);
		d.setFont(font2);
		m.setFont(font2);
		y.setFont(font2);
		
		
		this.add(limit);
		this.add(limitBox);
		this.add(soldToBox);
		this.add(inNumBox);
		this.add(dayBox);
		this.add(day);
		this.add(monthBox);
		this.add(month);
		this.add(yearBox);
		this.add(year);
		this.add(invoiceBox);
		this.add(prevDay);
		this.add(prev);
		this.add(nextDay);
		this.add(next);
		this.add(d);
		this.add(m);
		this.add(y);
		this.add(customer);
		this.add(customerName);
		this.add(total);
		this.add(balance);
		this.add(totalBox);
		this.add(balanceBox);
		this.add(insert);
		this.add(reset); 
		this.add(delete);
		inNumBox.setVisible(false);
		soldToBox.setVisible(false);
		
		totalBox.setEditable(false);
		setEditable(false);
		time = new Timer(300, this);
		this.addMouseListener(this);
		this.addMouseMotionListener(this);
		 
		debtPane = new JPanel();

			changeDebtPane(5000);
		scrollPane3 = new JScrollPane(debtPane);
		scrollPane3.setBounds(137, 294, 554, 125);
		
		scrollPane3.setVisible(false);
		
		newSales=new Inventory.GBPane();
		  
		scrollPane2 = new JScrollPane(newSales);
		scrollPane = new JScrollPane(viewPane);
		scrollPane.setBounds(137, 294, 554, 125);
		
		delete.addActionListener(this);
		 delete.setVisible(false);
		 AddInvoiceConfig(newSales);
		next.addActionListener(this);
		prev.addActionListener(this);
		prevDay.addActionListener(this);
		nextDay.addActionListener(this);
        customerName.addFocusListener(this);
        reset.addActionListener(this);
        insert.addActionListener(this);
        customerName.addKeyListener(this);
        totalBox.addKeyListener(this);
        balanceBox.addKeyListener(this);
        soldToBox.addKeyListener(this);
        inNumBox.addKeyListener(this);
        balanceBox.addKeyListener(this);	
        inNumBox.addFocusListener(this);
    	

		invoiceBox.addItemListener(this);
		dayBox.addItemListener(this);
		monthBox.addItemListener(this);
		yearBox.addItemListener(this);
		balanceBox.addFocusListener(this);
		balanceBox.addFocusListener(this);
        this.add(scrollPane);
        
		this.add(soldTo);
		this.add(inNum);
		this.add(scrollPane2);
		insert.setEnabled(false);
		reset.setVisible(false);
		limit.setVisible(false);
		limitBox.setVisible(false);
		
		
		scrollPane2.setVisible(false);
		balanceBox.setEditable(false);
		totalBox.setEditable(false);
		limitBox.addKeyListener(this);
		limitBox.addFocusListener(this);
		this.add(scrollPane3); 
	}
	

	public void setInComponents(boolean b) {

		dayBox.setVisible(b);
		monthBox.setVisible(b);
		yearBox.setVisible(b);
		d.setVisible(!b);
		m.setVisible(!b);
		y.setVisible(!b);

		prevDay.setVisible(b);
		nextDay.setVisible(b);

	}

	// repaint all the other containers
		public void paintAncestors(Container C) {
			while (C.getParent() != null) {
				C.repaint();
				C = C.getParent();
			}
		}

	public void setEditable(boolean b) {
		balanceBox.setEditable(b);
	}

	public void showButtons() {
		try {
			switch (userType) {

			case 4:
				inBtn = new Button("images/b2.png", "images/b2a.png",
						"images/b2.png");
				expBtn = new Button("images/b3.png", "images/b3a.png",
						"images/b3.png");
				usBtn = new Button("images/b5.png", "images/b5a.png",
						"images/b5.png");

			case 5:
				salesBtn = new Button("images/b1a.png", "images/b1.png",
						"images/b1.png");

			}
			viewSales = new Button("images/s1.png", "images/s1a.png",
					"images/s1.png");
			createIn = new Button("images/s2.png", "images/s2a.png",
					"images/s2.png");
			updIn = new Button("images/s3.png", "images/s3a.png",
					"images/s3.png");
			custBal = new Button("images/custombal.png",
					"images/custombala.png", "images/custombal.png");
			panel1 = ImageIO.read(new File("images/viewsales.png"));
			panel2 = ImageIO.read(new File("images/createinvoice.png"));
			panel3 = ImageIO.read(new File("images/updateinvoice.png"));
			panel4 = ImageIO.read(new File("images/customerBal.png"));

			logBtn = new Button("images/b7.png", "images/b7a.png",
					"images/b7.png");
			/*
			 * prevDay = new Button("images/prev.png", "images/preva.png",
			 * "images/prev.png"); prev = new Button("images/prev.png",
			 * "images/preva.png", "images/prev.png"); nextDay = new
			 * Button("images/nextday.png", "images/nextdaya.png",
			 * "images/nextday.png"); next = new Button("images/next.png",
			 * "images/nextb.png", "images/next.png");
			 */

		} catch (IOException e) {
			System.out.print("Image not found");
			e.printStackTrace();
		}

	}
	public ArrayList <String>getCustomerBal(String s,int i){
			ArrayList <String> L=new ArrayList();
			ResultSet RS;
	
			try{
				RS=db.MySQLSelect(s);
				while(RS.next()){
					L.add(RS.getString(i));
				}
			}catch (SQLException SQLe) {
				// TODO Auto-generated catch block
				error ="*Error: Error in Collecting Records";
			}
	
			return L;
		}
	
	public ArrayList<Invoice> getDBItems(String s) {
		ArrayList<Invoice> Records = new ArrayList<Invoice>();
		ResultSet RS, RInvoice;

		RInvoice = db.MySQLSelect(s);

		try {
			while (RInvoice.next())
				Records.add(new Invoice(RInvoice.getString(1), RInvoice
						.getString(3), RInvoice.getString(2), RInvoice
						.getDouble(4)));

			RInvoice.close();

			for (int ctr = 0; ctr < Records.size(); ctr++) {
				RS = db
						.MySQLSelect(
								"Select SaleID,Quantity, unit, productname, price from Sale,product where prCode=ProductCode AND ReceiptNum="
										+ Records.get(ctr).getReceiptNum());
				while (RS.next())
					Records.get(ctr).addSale(
							new Sale(RS.getString(1), RS.getString(4), RS
									.getString(3), RS.getDouble(2), RS
									.getDouble(5)));
			}
		} catch (SQLException SQLe) {
			// TODO Auto-generated catch block
			error = "*Error: Error in Collecting Records";
		}

		return Records;
	}

	// Display the Sales in the receipt
	private void recordPaneConfig(int n, boolean edit) {
		viewPane.removeAll();

		if (Invoices.size() > 0) {
			viewPane.setLayout(new GridLayout(
					Invoices.get(n).getSales().size() + 2, 4));
			viewPane.add(new JLabel("Quantity"));
			viewPane.add(new JLabel("Unit"));
			viewPane.add(new JLabel("Product"));
			viewPane.add(new JLabel("Price"));

			quantityBoxes = new ArrayList<JTextField>();
			unitBoxes = new ArrayList<JTextField>();
			prodBoxes = new ArrayList<JTextField>();
			priceBoxes = new ArrayList<JTextField>();

			Invoice I = Invoices.get(n);
			if (I != null && I.getCustomerName() != null)
				customerName.setText(I.getCustomerName() + "");
			else
				customerName.setText("");
			totalBox.setText("" + I.getTotal());
			balanceBox.setText("" + I.getBalance());

			for (int ctr = 0; ctr < I.getSales().size(); ctr++) {
				quantityBoxes.add(new JTextField(I.getSales().get(ctr)
						.getQuantity()
						+ ""));
				unitBoxes.add(new JTextField(I.getSales().get(ctr).getUnit()));
				prodBoxes
						.add(new JTextField(I.getSales().get(ctr).getProduct()));
				priceBoxes.add(new JTextField(I.getSales().get(ctr).getPrice()
						+ ""));

				viewPane.add(quantityBoxes.get(ctr));
				viewPane.add(unitBoxes.get(ctr));
				viewPane.add(prodBoxes.get(ctr));
				viewPane.add(priceBoxes.get(ctr));

				quantityBoxes.get(ctr).setEditable(edit);
				unitBoxes.get(ctr).setEditable(false);
				prodBoxes.get(ctr).setEditable(false);
				priceBoxes.get(ctr).setEditable(edit);

				quantityBoxes.get(ctr).addFocusListener(this);
				unitBoxes.get(ctr).addFocusListener(this);
				prodBoxes.get(ctr).addFocusListener(this);
				priceBoxes.get(ctr).addFocusListener(this);
				quantityBoxes.get(ctr).addKeyListener(this);
				priceBoxes.get(ctr).addKeyListener(this);
			}
			viewPane.add(enterQuan = new JTextField());
			viewPane.add(enterUnit = new JComboBox());
			viewPane.add(enterProd = new JComboBox());
			viewPane.add(enterPrice = new JTextField());

			enterQuan.setEditable(edit);
			enterUnit.setEnabled(edit);
			enterProd.setEnabled(edit);
			enterPrice.setEditable(edit);

			enterUnit.addActionListener(this);
			enterProd.addActionListener(this);

			try {
				setComboBoxItems(enterUnit);
				setComboBoxItems(enterProd);
			} catch (SQLException e) {
				error = "*Error: Error in collecting data";
			}

		} else
			error="*Error: No Sales Listed today";
	}

	private void ChangeViewPaneContents(String S, boolean edit) {

		customerName.setText(""); // Reset the textboxes to blanks
		totalBox.setText("");
		balanceBox.setText("");

		// get the records from the selected date
		Invoices = getDBItems(S);
		addInvoicestoCombobox();	 // Set the values of the combobox containing the Invoices
		recordPaneConfig(0, edit); // Display the Sales in the receipt
		newSales.paintAncestors();
	}

	private void changeDebtPane() {
		ArrayList<String> L1 = getCustomerBal(
				"SELECT CustomerName,sum(RemainingBalance) from Invoice group by customername",
				1);
		ArrayList<String> L2 = getCustomerBal(
				"SELECT CustomerName,sum(RemainingBalance) from Invoice group by customername",
				2);
		debtPane.removeAll();
		if (L1.size() > 0) {
			debtPane.setLayout(new GridLayout(L1.size() + 1, 2));
			debtPane.add(new JLabel("Customer Name"));
			debtPane.add(new JLabel("Balance"));

			for (int ctr = 0; ctr < L1.size(); ctr++) {
				debtPane.add(new JLabel(L1.get(ctr)));
				debtPane.add(new JTextField(L2.get(ctr)));
			}

		}

	}

	private void changeDebtPane(double d) {
		ArrayList<String> L1 = getCustomerBal(
				"SELECT CustomerName,sum(RemainingBalance) from Invoice where RemainingBalance >="
						+ d + "group by customername", 1);
		ArrayList<String> L2 = getCustomerBal(
				"SELECT CustomerName,sum(RemainingBalance) from Invoice where RemainingBalance >="
						+ d + "group by customername", 2);
		debtPane.removeAll();
		if (L1.size() > 0) {
			debtPane.setLayout(new GridLayout(L1.size() + 1, 2));
			debtPane.add(new JLabel("Customer Name"));
			debtPane.add(new JLabel("Balance"));

			for (int ctr = 0; ctr < L1.size(); ctr++) {
				debtPane.add(new JLabel(L1.get(ctr)));
				debtPane.add(new JLabel(L2.get(ctr)));
			}

		}

	}

	public void manageViewPaneVisibility(boolean view) {

		if (invoiceBox.getItemCount() > 0)
			for (int ctr = 0; ctr < Invoices.get(invoiceBox.getSelectedIndex())
					.getSales().size(); ctr++) {
				quantityBoxes.get(ctr).setEditable(!view);
				priceBoxes.get(ctr).setEditable(!view);
			}

		customerName.setEditable(!view);
		balanceBox.setEditable(!view);
		if (enterQuan != null) {
			enterQuan.setEditable(!view);
			enterUnit.setEnabled(!view);
			enterProd.setEnabled(!view);
			enterPrice.setEditable(false);
			delete.setVisible(!view);
		}
	}

	public void setComboBoxItems(JComboBox cb) throws SQLException {
		cb.removeAllItems();
		if (cb == monthBox) {
			cb.addItem("January");
			cb.addItem("Febuary");
			cb.addItem("March");
			cb.addItem("April");
			cb.addItem("May");
			cb.addItem("June");
			cb.addItem("July");
			cb.addItem("August");
			cb.addItem("September");
			cb.addItem("October");
			cb.addItem("November");
			cb.addItem("December");

			ResultSet RS = db.MySQLSelect("Select Month(now());"), RY, RD;
			RS.first();
			cb.setSelectedIndex(RS.getInt(1) - 1);

			RY = db.MySQLSelect("Select Year(now());");
			RY.first();

			int limit, ctr;

			if (RS.getInt(1) == 1 || RS.getInt(1) == 3 || RS.getInt(1) == 5
					|| RS.getInt(1) == 7 || RS.getInt(1) == 8
					|| RS.getInt(1) == 10 || RS.getInt(1) == 12)
				limit = 31;
			else if (RS.getInt(1) == 2)
				if (RY.getInt(1) % 4 != 0)
					limit = 28;
				else
					limit = 29;
			else
				limit = 30;

			for (ctr = 1; ctr <= limit; ctr++)
				dayBox.addItem("" + ctr);
			RS.close();
			RY.close();

			RD = db.MySQLSelect("Select Day(now());");
			RD.first();

			dayBox.setSelectedItem(RD.getString(1));
			RD.close();

		} else if (cb == yearBox) {
			ResultSet RS = db
					.MySQLSelect("Select Year(TimeRecorded) from Inventory group by year(TimeRecorded);");

			while (RS.next())
				cb.addItem(RS.getString(1));
			cb.setSelectedIndex(cb.getItemCount() - 1);
			RS.close();
		}

		else if (cb == invoiceBox)
			addInvoicestoCombobox();
		else if ((addUnits != null && addUnits.contains(cb)) || cb == enterUnit) {
			cb.addItem("Select Unit");

			ResultSet RS = db
					.MySQLSelect("SELECT Unit from Product group by Unit;");

			while (RS.next())
				cb.addItem(RS.getString(1));
			RS.close();
		} else if ((addProd != null && addProd.contains(cb)) || cb == enterProd) {
			int i;
			ResultSet RS = null;
			cb.addItem("Select Product");
			if (cb != enterProd) {
				i = addProd.indexOf(cb);

				if (addUnits.get(i).getSelectedIndex() > 0) {
					RS = db.MySQLSelect("SELECT ProductName from Product where Unit='"
							+ addUnits.get(i).getSelectedItem().toString()
							+ "';");
				}
			} else if (enterUnit.getSelectedIndex() > 0)
				RS = db.MySQLSelect("SELECT ProductName from Product where Unit='"
						+ enterUnit.getSelectedItem().toString() + "';");

			if (RS != null) {
				while (RS.next())
					cb.addItem(RS.getString(1));
				RS.close();
			}
		}
	}
	public void addInvoicestoCombobox() {
		if (invoiceBox.getItemCount() > 0)
			invoiceBox.removeAllItems();
		for (int ctr = 0; ctr < Invoices.size(); ctr++)
			invoiceBox.addItem(Invoices.get(ctr).getReceiptNum() + " "
					+ Invoices.get(ctr).getCustomerName());
	}

	public void addSalesRow(GBPane gb, int i) {
		newQuans.add(new JTextField("", 5));
		addUnits.add(new JComboBox());
		addProd.add(new JComboBox());
		newPrices.add(new JTextField("", 5));

		try {
			setComboBoxItems(addUnits.get(i));
			setComboBoxItems(addProd.get(i));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
		}

		gb.addComponent(newQuans.get(i), 0, i + 1, 1, 1, 0, 0,
				GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		gb.addComponent(addUnits.get(i), 1, i + 1, 1, 1, 0, 0,
				GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		gb.addComponent(addProd.get(i), 2, i + 1, 1, 1, 0, 0,
				GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);
		gb.addComponent(newPrices.get(i), 3, i + 1, 1, 1, 0, 0,
				GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST);

		gb.paintAncestors();

		newPrices.get(i).setEditable(false);

		addUnits.get(i).addActionListener(this);
		addProd.get(i).addActionListener(this);
		newQuans.get(i).addFocusListener(this);
		newPrices.get(i).addFocusListener(this);
		newQuans.get(i).addKeyListener(this);
		newPrices.get(i).addKeyListener(this);
	}

	public void AddInvoiceConfig(GBPane gb) {
		gb.removeAll();

		gb.addComponent(new JLabel("Quantity "), 0, 0, 1, 1, 0, 0,
				GridBagConstraints.NONE, GridBagConstraints.WEST);
		gb.addComponent(new JLabel("Unit "), 1, 0, 1, 1, 0, 0,
				GridBagConstraints.NONE, GridBagConstraints.WEST);
		gb.addComponent(new JLabel("Product "), 2, 0, 1, 1, 0, 0,
				GridBagConstraints.NONE, GridBagConstraints.WEST);
		gb.addComponent(new JLabel("Price "), 3, 0, 1, 1, 0, 0,
				GridBagConstraints.NONE, GridBagConstraints.WEST);

		newQuans = new ArrayList<JTextField>();
		addUnits = new ArrayList<JComboBox>();
		addProd = new ArrayList<JComboBox>();
		newPrices = new ArrayList<JTextField>();

		addSalesRow(gb, 0);
	}

	public void ResetInsertion() {
		AddInvoiceConfig(newSales);
		soldToBox.setText("");
		totalBox.setText("");
		balanceBox.setText("");
		inNumBox.setText("");
		newSales.paintAncestors();
		insert.setEnabled(false);
		balanceBox.setEditable(false);
	}

	public void InsertReceipt(){
		String name;
		error="";
			
		
		if(soldToBox.getText().length()==0){
			name="";
			error="*Error:No  customer name";
		}
		
		else{
			name=soldToBox.getText();
			int iRec=db.MySQLInsert("Insert INTO Invoice values ('"+inNumBox.getText()+"',curDate(),'"+name+"',"+balanceBox.getText()
					+");"),cnt;
			
			if(iRec>0){
				
				ResultSet RS;
				String id="";
				for(int ctr=0;ctr<addUnits.size()-1;ctr++){
					RS=db.MySQLSelect("SELECT ProductCode from Product where unit='"+addUnits.get(ctr).getSelectedItem().toString()
						+"' AND productname='"+addProd.get(ctr).getSelectedItem().toString()+"';");
					
					try {
						
						while(RS.next())
							id=RS.getString(1);
						RS.close();
						cnt=db.MySQLInsert("INSERT into Sale values(now()+'"+ctr+"',"+newQuans.get(ctr).getText()
								+","+newPrices.get(ctr).getText()+",'"+inNumBox.getText()+"','"+id+"');");
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						error="*Error: Adding incomplete";
					}
					
				}
				
				ResetInsertion();
			}
		}
	}
	

	// method that changes the DayBox based on the month
	public void dayBoxConfig(int month) {
		int limit, year = Integer.valueOf(yearBox.getSelectedItem().toString()), MaxDay = dayBox
				.getItemCount(), Day = dayBox.getSelectedIndex() + 1;
		// Determine month to determine number of days
		if (month == 0 || month == 2 || month == 4 || month == 6 || month == 7
				|| month == 9 || month == 11)
			limit = 31;
		else if (month == 1)
			if (year % 4 != 0)
				limit = 28;
			else
				limit = 29;
		else
			limit = 30;

		dayBox.removeItemListener(this);
		// DayBox.setSelectedIndex(0);

		if (MaxDay < limit)
			for (int ctr = MaxDay + 1; ctr <= limit; ctr++)
				dayBox.addItem("" + ctr);
		else if (MaxDay > limit) {
			dayBox.removeAllItems();
			for (int ctr = 1; ctr <= limit; ctr++)
				dayBox.addItem("" + ctr);
			while (Day > limit)
				Day--;
			dayBox.setSelectedItem("" + Day);
		}
		monthBox.addItemListener(this);
		dayBox.addItemListener(this);
	}

	// Method that responds to the next and previous day buttons
	public void nextPrevDay(int change) {
		int month;
		if (change > 0) {
			if (dayBox.getSelectedIndex() < dayBox.getItemCount() - change)
				dayBox.setSelectedIndex(dayBox.getSelectedIndex() + change);
			else if (monthBox.getSelectedIndex() < monthBox.getItemCount()
					- change) {
				monthBox.removeItemListener(this);
				monthBox.setSelectedIndex(monthBox.getSelectedIndex() + change);
				month = monthBox.getSelectedIndex();

				dayBoxConfig(month);

				dayBox.setSelectedIndex(0);
			} else {
				yearBox.removeItemListener(this);
				yearBox.addItem(""
						+ (Integer
								.valueOf(yearBox.getSelectedItem().toString()) + 1));
				yearBox.setSelectedIndex(yearBox.getItemCount() - 1);
				monthBox.setSelectedIndex(0);
				dayBox.setSelectedIndex(0);
				yearBox.addItemListener(this);

			}

		} else if (change < 0) {
			if (dayBox.getSelectedIndex() > 0)
				dayBox.setSelectedIndex(dayBox.getSelectedIndex() + change);
			else if (monthBox.getSelectedIndex() > 0) {
				monthBox.removeItemListener(this);
				monthBox.setSelectedIndex(monthBox.getSelectedIndex() + change);
				month = monthBox.getSelectedIndex();
				dayBoxConfig(month);

				dayBox.setSelectedIndex(dayBox.getItemCount() - 1);
			} else if (yearBox.getSelectedIndex() > 0)
				yearBox.setSelectedIndex(yearBox.getSelectedIndex() + change);
			else
				error = "*Error: No more record in the previous Years";
		}
	}

	private double calculateNewInvoiceCost() {
		double sum = 0;

		for (int ctr = 0; ctr < newPrices.size() - 1; ctr++)
			sum += Double.valueOf(newPrices.get(ctr).getText());
		return sum;
	}

	private double getProductCost(String Unit, String Product)
			throws SQLException {
		ResultSet RS;
		double cost = 1;
		RS = db.MySQLSelect("SELECT unitPrice from Product where unit='" + Unit
				+ "' AND ProductName='" + Product + "';");
		while (RS.next())
			cost = RS.getDouble(1);

		return cost;
	}

	public void deleteSale(int i, JTextField txt) {
		if (quantityBoxes != null
				&& (quantityBoxes.contains(txt) || priceBoxes.contains(txt))) {
			try {
				db.MySQLUpdate("DELETE from Sale where SaleID='"
						+ selected.getSales().get(i).getID() + "';");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			selected.getSales().remove(i);
			recordPaneConfig(invoiceBox.getSelectedIndex(), true);
			paintAncestors(viewPane);

		} else {

			// Remove from panel
			newSales.remove(newQuans.get(i));
			newSales.remove(newPrices.get(i));
			newSales.remove(addProd.get(i));
			newSales.remove(addUnits.get(i));

			// Remove sale from list
			newQuans.remove(i);
			newPrices.remove(i);
			addUnits.remove(i);
			addProd.remove(i);

			calculateNewInvoiceCost();
			newSales.paintAncestors();
		}
	}

	@Override
	public void itemStateChanged(ItemEvent IE) {
		// TODO Auto-generated method stub
		error ="";
		if (IE.getSource() == monthBox) {
			monthBox.removeItemListener(this);
			dayBoxConfig(monthBox.getSelectedIndex());
		}

		if (IE.getSource() == invoiceBox && invoiceBox.getItemCount() > 0) {
			recordPaneConfig(invoiceBox.getSelectedIndex(),
					!monthBox.isVisible());
			paintAncestors(viewPane);
			selected = Invoices.get(invoiceBox.getSelectedIndex());
		} else if (IE.getSource() == dayBox || IE.getSource() == monthBox
				|| IE.getSource() == yearBox) {

			// get the records from the selected date
			ChangeViewPaneContents(
					"SELECT * from Invoice where dateofReceipt='"
							+ yearBox.getSelectedItem().toString() + "-"
							+ (monthBox.getSelectedIndex() + 1) + "-"
							+ dayBox.getSelectedItem().toString() + "';", false);
		}
	}

	public void deleteInvoice(){
		error = "";
		try {
			db.MySQLUpdate("DELETE from Invoice where receiptNumber='"+selected.getReceiptNum()+"';");
			Invoices.remove(selected);
			//Must only delete invoices of the current date
			ChangeViewPaneContents("SELECT * from Invoice where dateofReceipt=CurDate()",true);
		} catch (SQLException SE) {
			error="*Error: Delete failed";
		}
	}

	@Override
	public void actionPerformed(ActionEvent AE) {
		// TODO Auto-generated method stub
		repaint();
		if (scrollPane != null) {
			scrollPane.revalidate();
			scrollPane2.revalidate();
			scrollPane3.revalidate();

		}
		switch (curPanel) {

		case 0:
			viewSales.setCurImg(1);
			customerName.setEditable(false);
			break;
		case 1:
			createIn.setCurImg(1);

			break;
		case 2:
			updIn.setCurImg(1);
			customerName.setEditable(true);
			break;
		case 3:
			custBal.setCurImg(1);
			manageViewPaneVisibility(true);
			break;
		} 
  	    if(AE.getSource()==next&&invoiceBox.getSelectedIndex()<invoiceBox.getItemCount()-1)
			invoiceBox.setSelectedIndex(invoiceBox.getSelectedIndex()+1);
		else if(AE.getSource()==prev&&invoiceBox.getSelectedIndex()>0)
			invoiceBox.setSelectedIndex(invoiceBox.getSelectedIndex()-1);
		else if(AE.getSource()==prevDay)
			nextPrevDay(-1);
		else if(AE.getSource()==nextDay)
			nextPrevDay(1);
		else if(AE.getSource()==delete)
			deleteInvoice();
		else if(AE.getSource()==enterUnit)
			try {
				error="";
				setComboBoxItems(enterProd);
			} catch (SQLException e) {
				error="*Error: No product with that unit";
			}
		else if(AE.getSource()==enterProd){
			double cost=1,q=1;
			String fid="",now=db.getMysqlNow();
			if(balanceBox!=null)
				balanceBox.setEditable(true);

            if(enterQuan.getText().length()>0)
                  try{
                      q=Double.valueOf(enterQuan.getText());
                      error="";
                  }catch(NumberFormatException NE){
                       error="Type numbers for quantity";
                       q=1;
                       enterQuan.setText(""+1);
                     }
			if(enterUnit.getSelectedIndex()>0&&enterQuan.getText().length()==0)
				enterQuan.setText(""+1);
			
			if(enterProd.getSelectedIndex()>0){
				try{
					
					ResultSet RS=db.MySQLSelect("SELECT ProductCode from Product where unit='"+enterUnit.getSelectedItem().toString()
							+"' AND productname='"+enterProd.getSelectedItem().toString()+"';");
					
					while(RS.next())
						fid=RS.getString(1);
					RS.close();
					
					if(enterQuan.getText().length()>0)
						cost=getProductCost(enterUnit.getSelectedItem().toString(), enterProd.getSelectedItem().toString())*Double.valueOf(enterQuan.getText());
					else cost=getProductCost(enterUnit.getSelectedItem().toString(), enterProd.getSelectedItem().toString());
					
					
					enterPrice.setText(""+cost);
					db.MySQLInsert("INSERT into Sale values('"+now+"', "+enterQuan.getText()
							+","+enterPrice.getText()+","+selected.getReceiptNum()+",'"+fid+"');");
					selected.getSales().add(new Sale(now, enterProd.getSelectedItem().toString(),enterUnit.getSelectedItem().toString(), Double.valueOf(enterQuan.getText()), cost, selected));
					error="";
				}catch (SQLException SE) {
					error="*Error: Price not found";
					cost=1;
				}
				enterPrice.setEditable(true);
				enterPrice.setText(""+cost);	//get the cost of the sale
				
				//Change the panel containing the recipt to correspond to the database
				recordPaneConfig(invoiceBox.getSelectedIndex(), true);
			
			}
		}
		else if(addUnits!=null&&addUnits.contains(AE.getSource())){
			int i=addUnits.indexOf(AE.getSource());
			try {
				setComboBoxItems(addProd.get(i));
				error="";
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				error="*Error: No Product with that unit";
			}
		}
		else if(addProd!=null&&addProd.contains(AE.getSource())){
			int i=addProd.indexOf(AE.getSource());
			double cost=0,q;

                        try{
                            q=Double.valueOf(newQuans.get(i).getText());

                        }
                        catch(NumberFormatException NE){
                            q=1;
                            newQuans.get(i).setText(""+q);
                        }

			if((newQuans.get(i).getText().length()==0||q<=0)&&addUnits.get(i).getSelectedIndex()>0)
				newQuans.get(i).setText(""+1);
			
			if(addProd.get(i).getSelectedIndex()>0){
				try{
					cost=getProductCost(addUnits.get(i).getSelectedItem().toString(), addProd.get(i).getSelectedItem().toString())*Double.valueOf(newQuans.get(i).getText());
					
				}catch (SQLException SE) {
					error="*Error: Price not found";
					cost=0;
				}
				newPrices.get(i).setEditable(true);
				newPrices.get(i).setText(""+cost);	//get the cost of the sale
				
				if(i==addProd.size()-1)
					addSalesRow(newSales, i+1);
				
				totalBox.setText(""+calculateNewInvoiceCost());	//Update the total
				if(inNumBox.getText().length()>0){
					insert.setEnabled(true);
					balanceBox.setEditable(true);
				}
			}
			
		}
		else if(AE.getSource()==reset)
			ResetInsertion();
		else if(AE.getSource()==insert)
			InsertReceipt();
  	   
		if (scrollPane != null) {
			scrollPane.revalidate();
			scrollPane2.revalidate();

			scrollPane3.revalidate();
		}
	}

	public void paint(Graphics g) {
		super.paint(g);
		Graphics2D g2D = (Graphics2D) g;
		time.start();
		g2D.drawImage(bg, 0, 0, null);

		switch (userType) {
		case 4:
			g2D.drawImage(usBtn.getCurImg(), 497, 8, null);
			g2D.drawImage(inBtn.getCurImg(), 269, 8, null);
			g2D.drawImage(expBtn.getCurImg(), 383, 8, null);

		case 5:
			g2D.drawImage(salesBtn.getCurImg(), 145, 8, null);

		}
		g2D.drawImage(logBtn.getCurImg(), 611, 8, null);

		Font font = new Font("Calibri", Font.PLAIN, 20);
		g2D.drawImage(viewSales.getCurImg(), 10, 100, null);
		g2D.drawImage(createIn.getCurImg(), 10, 200, null);
		g2D.drawImage(updIn.getCurImg(), 10, 300, null);
		g2D.drawImage(custBal.getCurImg(), 10, 400, null);

		g2D.setColor(Color.RED);
		g2D.setFont(font);

		if (curPanel == 0) {
			g2D.drawImage(panel1, 125, 105, null);
			g2D.drawString(error, 297, 167);

		}
		if (curPanel == 1) {
			g2D.drawImage(panel2, 125, 105, null);

		}
		if (curPanel == 2) {
			g2D.drawImage(panel3, 125, 105, null);

		}
		if (curPanel == 3) {
			g2D.drawImage(panel4, 125, 105, null);

		}
		Font font2 = new Font("Calibri", Font.PLAIN, 20);

		g2D.setColor(Color.RED);
		g2D.setFont(font2);

		g2D.drawString(error, 297, 167);

	}

	@Override
	public void mouseClicked(MouseEvent m) {
		// TODO Auto-generated method stubn
		switch (userType) {
		case 4:
			if (m.getX() >= 504 && m.getX() <= 581 && m.getY() >= 7
					&& m.getY() <= 85)// within the boundaries of us btn
				cards.show(parent, "users");
			else if (m.getX() >= 275 && m.getX() <= 354 && m.getY() >= 7
					&& m.getY() <= 88)// within the boundaries of inventory btn
				cards.show(parent, "inventory");
			else if (m.getX() >= 390 && m.getX() <= 469 && m.getY() >= 8
					&& m.getY() <= 86)// within the boundaries of exp btn
				cards.show(parent, "expense");

			break;
		}
		if (m.getX() >= 617 && m.getX() <= 698 && m.getY() >= 9
				&& m.getY() <= 85) {// within the boundaries of log out btn
			final JFrame frame2 = new JFrame("Confirm Action");

			JLabel label = new JLabel();
			JLabel label2 = new JLabel("Are you sure you want to log out?");
			JButton yes = new JButton("Yes");
			JButton no = new JButton("No");
			yes.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					// TODO Auto-generated method stub
					new MainFrame();
					frame.dispose();
					frame2.dispose();
				}
			});
			yes.setIcon(new ImageIcon("Images/yes.png"));
			no.setIcon(new ImageIcon("Images/no.png"));

			no.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					// TODO Auto-generated method stub
					frame2.dispose();
				}
			});

			label2.setFont(new Font(Font.SERIF, Font.PLAIN, 17));

			JPanel panel = new JPanel();
			ImageIcon confirm;
			confirm = new ImageIcon("Images/confirmaction.png");
			label.setIcon(confirm);

			panel.add(label);
			panel.add(label2);
			panel.add(yes);
			panel.add(no);

			label.setBounds(26, 20, 120, 120);
			label2.setBounds(145, 40, 250, 30);
			yes.setBounds(160, 105, 80, yes.getPreferredSize().height);
			no.setBounds(260, 105, 80, no.getPreferredSize().height + 2);

			panel.setLayout(null);
			frame2.add(panel);
			frame2.setVisible(true);
			frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			frame2.setSize(400, 200);
			frame2.setLocationRelativeTo(null);

		}

		if (m.getX() >= 17 && m.getX() <= 94 && m.getY() >= 100
				&& m.getY() <= 181) {// within the boundaries of view sales btn
			error = "";
			scrollPane.revalidate();
			scrollPane2.revalidate();
			curPanel = 0;
			viewSales.setCurImg(1);
			createIn.setCurImg(0);
			updIn.setCurImg(0);
			custBal.setCurImg(0);
			setInComponents(true);
			delete.setVisible(false);
			scrollPane3.setVisible(false);
			invoiceBox.setVisible(true);
			prev.setVisible(true);
			next.setVisible(true);
			customer.setVisible(true);
			customerName.setVisible(true);
			setEditable(false);
			soldTo.setVisible(false);
			inNum.setVisible(false);
			soldToBox.setVisible(false);
			inNumBox.setVisible(false);
			ChangeViewPaneContents("SELECT * from Invoice where dateofReceipt='"+
					yearBox.getSelectedItem().toString()+"-"+(monthBox.getSelectedIndex()+1)+"-"+dayBox.getSelectedItem().toString()+"';",false);
			manageViewPaneVisibility(true);insert.setVisible(false);
			reset.setVisible(false);
			scrollPane.setVisible(true);
			scrollPane2.setVisible(false);

			total.setVisible(true);
			balance.setVisible(true);
			balanceBox.setVisible(true);
			totalBox.setVisible(true);
			limit.setVisible(false);
			limitBox.setVisible(false);


		} else if (m.getX() >= 17 && m.getX() <= 94 && m.getY() >= 200
				&& m.getY() <= 281) {// create
		
			totalBox.setText("");
			balanceBox.setText("0.0");
			error = "";
			scrollPane2.revalidate();
			curPanel = 1;
			
			scrollPane3.setVisible(false);
			viewSales.setCurImg(0);
			createIn.setCurImg(1);
			updIn.setCurImg(0);
			custBal.setCurImg(0);

			invoiceBox.setVisible(false);
			prev.setVisible(false);
			next.setVisible(false);
			customer.setVisible(false);
			customerName.setVisible(false);
			setEditable(false);
			inNumBox.setVisible(true);
			soldToBox.setVisible(true);

			soldTo.setVisible(true);
			inNum.setVisible(true);
			scrollPane.setVisible(false);
			scrollPane2.setVisible(true);
			scrollPane2.setBounds(137, 245, 554, 175);
			insert.setVisible(true);
			
			reset.setVisible(true);
			setInComponents(false);

			delete.setVisible(false);
			total.setVisible(true);
			balance.setVisible(true);
			balanceBox.setVisible(true);
			totalBox.setVisible(true);
			limit.setVisible(false);
			limitBox.setVisible(false);
			customerName.setText(""+invoiceBox.getSelectedItem());
		}

		else if (m.getX() >= 17 && m.getX() <= 94 && m.getY() >= 300
				&& m.getY() <= 377) {//manage
			error = "";
			scrollPane.revalidate();
			curPanel = 2;

			scrollPane3.setVisible(false);
			insert.setVisible(false);
			viewSales.setCurImg(0);
			createIn.setCurImg(0);
			updIn.setCurImg(1);
			custBal.setCurImg(0);
			invoiceBox.setVisible(true);
			prev.setVisible(true);
			next.setVisible(true);
			customer.setVisible(true);
			customerName.setVisible(true);
			setEditable(true);

			scrollPane.setVisible(true);
			scrollPane2.setVisible(false);
			soldTo.setVisible(false);
			inNum.setVisible(false);
			soldToBox.setVisible(false);
			inNumBox.setVisible(false);
			scrollPane.setBounds(137, 294, 554, 125);
			insert.setVisible(false);
			reset.setVisible(false);

			delete.setVisible(true);
			total.setVisible(true);
			balance.setVisible(true);
			balanceBox.setVisible(true);
			totalBox.setVisible(true);
			// Must only modify sales of the current date
			ChangeViewPaneContents("SELECT * from Invoice where dateofReceipt=CurDate()",true);
			manageViewPaneVisibility(false);
			limit.setVisible(false);
			limitBox.setVisible(false);

		} else if (m.getX() >= 17 && m.getX() <= 94 && m.getY() >= 399
				&& m.getY() <= 478) {// customer balance
			error = "";

			delete.setVisible(false);
			scrollPane3.setVisible(true);
			curPanel = 3;
			viewSales.setCurImg(0);
			createIn.setCurImg(0);
			updIn.setCurImg(0);
			custBal.setCurImg(1);
			insert.setVisible(false);
			reset.setVisible(false);
			scrollPane.setVisible(false);
			scrollPane2.setVisible(false);
			limit.setVisible(true);
			limitBox.setVisible(true);

			manageViewPaneVisibility(false);
			inNumBox.setVisible(false);
			soldToBox.setVisible(false);
			prevDay.setVisible(false);
			nextDay.setVisible(false);
			prev.setVisible(false);
			next.setVisible(false);
			setInComponents(false);
			soldTo.setVisible(false);
			inNum.setVisible(false);
			total.setVisible(false);
			balance.setVisible(false);
			balanceBox.setVisible(false);
			totalBox.setVisible(false);
			customer.setVisible(false);
			customerName.setVisible(false);
			invoiceBox.setVisible(false);

		}

	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseDragged(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseMoved(MouseEvent m) {
		// TODO Auto-generated method stub
		switch (userType) {

		case 4:
			if (m.getX() >= 275 && m.getX() <= 354 && m.getY() >= 7
					&& m.getY() <= 88)// within the boundaries of inventory btn
				inBtn.setCurImg(1);
			else if (m.getX() >= 390 && m.getX() <= 469 && m.getY() >= 8
					&& m.getY() <= 86)// within the boundaries of exp btn
				expBtn.setCurImg(1);
			else if (m.getX() >= 504 && m.getX() <= 581 && m.getY() >= 7
					&& m.getY() <= 85)// within the boundaries of us btn
				usBtn.setCurImg(1);
			else if (m.getX() >= 617 && m.getX() <= 698 && m.getY() >= 9
					&& m.getY() <= 85)// within the boundaries of log out btn
				logBtn.setCurImg(1);

			else {
				salesBtn.setCurImg(0);
				inBtn.setCurImg(0);
				expBtn.setCurImg(0);
				usBtn.setCurImg(0);
				logBtn.setCurImg(0);
			}
			break;

		case 5:

			if (m.getX() >= 617 && m.getX() <= 698 && m.getY() >= 9
					&& m.getY() <= 85)// within the boundaries of log out btn
				logBtn.setCurImg(1);
			else
				salesBtn.setCurImg(0);
			logBtn.setCurImg(0);

		}
		if (m.getX() >= 17 && m.getX() <= 94 && m.getY() >= 100
				&& m.getY() <= 181)// within the boundaries of view sales btn
			viewSales.setCurImg(1);
		else if (m.getX() >= 17 && m.getX() <= 94 && m.getY() >= 200
				&& m.getY() <= 281)
			createIn.setCurImg(1);
		else if (m.getX() >= 17 && m.getX() <= 94 && m.getY() >= 300
				&& m.getY() <= 377)
			updIn.setCurImg(1);
		else if (m.getX() >= 17 && m.getX() <= 94 && m.getY() >= 399
				&& m.getY() <= 478)
			custBal.setCurImg(1);
		else {
			viewSales.setCurImg(0);
			createIn.setCurImg(0);
			updIn.setCurImg(0);
			custBal.setCurImg(0);
		}

	}

	@Override
	public void focusGained(FocusEvent FE) {
		int i;

		if (FE.getSource() == enterQuan)
			if (enterQuan.getText().length() > 0)
				enterQuan.setToolTipText("" + enterQuan.getText());
			else
				enterQuan.setToolTipText("1");

		else if (newQuans.contains(FE.getSource())) {
			i = newQuans.indexOf(FE.getSource());
			double d;
			if (newQuans.get(i).getText().length() > 0) {
				try {
					d = Double.valueOf(newQuans.get(i).getText());

				} catch (NumberFormatException NE) {
					d = 1;
				}
				newQuans.get(i).setToolTipText("" + d);
			} else
				newQuans.get(i).setToolTipText("1");
		} else if (newPrices.contains(FE.getSource())) {
			i = newPrices.indexOf(FE.getSource());
			if (newQuans.get(i).getText().length() > 0)
				newPrices.get(i)
						.setToolTipText("" + newPrices.get(i).getText());
			else
				newPrices.get(i).setToolTipText("1");
		}
		
	}

	@Override
	public void focusLost(FocusEvent FE) {
		double cost = 1;
		int i;

		error = "";
		if (quantityBoxes != null && quantityBoxes.contains(FE.getSource())) {
			i = quantityBoxes.indexOf(FE.getSource());
			double q = selected.getSales().get(i).getQuantity();

			try {
				q = Double.valueOf(quantityBoxes.get(i).getText());
			} catch (NumberFormatException NE) {
				q = selected.getSales().get(i).getQuantity();
				quantityBoxes.get(i).setText("" + q);
			}

			if (quantityBoxes.get(i).getText().length() == 0) {
				error = "*Error: Do not put empty values on Quantity!";
				quantityBoxes.get(i).setText(
						"" + selected.getSales().get(i).getQuantity());
			} else if (q <= 0) {
				error = "*Error: Enter a number greater than 0!";
				quantityBoxes.get(i).setText(
						"" + selected.getSales().get(i).getQuantity());
			} else
				try {
					selected.getSales()
							.get(i)
							.setQuantity(
									Double.valueOf(quantityBoxes.get(i)
											.getText()));
					cost = getProductCost(selected.getSales().get(i).getUnit(),
							selected.getSales().get(i).getProduct())
							* Double.valueOf(quantityBoxes.get(i).getText());
					selected.getSales().get(i).setPrice(cost);
					priceBoxes.get(i).setText("" + cost);
					db.MySQLUpdate("UPDATE Sale SET Quantity="
							+ quantityBoxes.get(i).getText() + ", price="
							+ cost + " where SaleID='"
							+ selected.getSales().get(i).getID() + "';");
					totalBox.setText("" + selected.getTotal());
				} catch (SQLException SQLEx) {
					error = "*Error: " + SQLEx;
					quantityBoxes.get(i).setText(
							selected.getSales().get(i).getQuantity() + "");
				}
		} else if (priceBoxes != null && priceBoxes.contains(FE.getSource())) {
			i = priceBoxes.indexOf(FE.getSource());
			double p = selected.getSales().get(i).getPrice();
			try {
				p = Double.valueOf(priceBoxes.get(i).getText());
			} catch (NumberFormatException NE) {
				p = selected.getSales().get(i).getPrice();
				priceBoxes.get(i).setText(
						"" + selected.getSales().get(i).getPrice());
			}

			if (priceBoxes.get(i).getText().length() == 0) {
				error = "*Error: Do not put empty values on Price!";
				priceBoxes.get(i).setText("" + p);
			} else if (p <= 0) {
				error = "*Error: Enter a number greater than 0!";
				priceBoxes.get(i).setText(
						"" + selected.getSales().get(i).getPrice());
			} else
				try {
					selected.getSales().get(i).setPrice(p);
					db.MySQLUpdate("UPDATE Sale SET Price="
							+ p
							+ " where SaleID='"
							+ Invoices.get(invoiceBox.getSelectedIndex())
									.getSales().get(i).getID() + "';");
					totalBox.setText("" + selected.getTotal());
				} catch (Exception SQLEx) {

					error = "*Error: " + SQLEx;
					priceBoxes.get(i).setText(
							selected.getSales().get(i).getPrice() + "");
				}
		} else if (FE.getSource() == customerName
				&& invoiceBox.getItemCount() > 0) {
			try {
				selected.setCustomerName(customerName.getText());
				invoiceBox.setSelectedItem(customerName.getText());
				db.MySQLUpdate("UPDATE Invoice SET CustomerName='"
						+ customerName.getText() + "' where receiptNumber='"
						+ selected.getReceiptNum() + "';");
			} catch (SQLException SQLEx) {
				error = "*Error: " + SQLEx;
				customerName.setText(selected.getCustomerName());
			}
		} else if (FE.getSource() == balanceBox
				&& invoiceBox.getItemCount() > 0) {
			try {
				selected.setBalance(Double.valueOf(balanceBox.getText()));
				if (Double.valueOf(balanceBox.getText()) < 0) {
					error = "*Error: Balance must not be less than zero";
					balanceBox.setText("" + selected.getBalance());
				}
				db.MySQLUpdate("UPDATE Invoice SET remainingBalance='"
						+ customerName.getText() + "' where receiptNumber='"
						+ selected.getReceiptNum() + "';");
			} catch (SQLException SQLEx) {
				error = "*Error: " + SQLEx;
				balanceBox.setText(0.0+"");
			}
		} else if (newQuans.contains(FE.getSource())) {
			double oldCost = 0, q = 1;
			i = newQuans.indexOf(FE.getSource());

			if (newQuans.get(i).getText().length() > 0 && q < 0) {
				newQuans.get(i).setText(
						"" + (Double.valueOf(newQuans.get(i).getText()) * -1));
				error = "*Error: No negative values for quantity";
			}
			if (newQuans.get(i).getText().length() > 0
					&& addUnits.get(i).getSelectedIndex() > 0
					&& addProd.get(i).getSelectedIndex() > 0) {
				try {
					cost = getProductCost(addUnits.get(i).getSelectedItem()
							.toString(), addProd.get(i).getSelectedItem()
							.toString());
					totalBox.setText(""
							+ (Double.valueOf(newPrices.get(i).getText()) - oldCost)); // Reduce
																						// the
																						// total
				} catch (SQLException SE) {
					error = "*Error: Price not found";
					newQuans.get(i).setText("" + oldCost / cost);
					cost = oldCost;

				}
				cost *= q;
				newPrices.get(i).setText("" + cost); // get the cost of the sale
				totalBox.setText("" + calculateNewInvoiceCost()); // Update the
																	// total
			}

		} else if (newPrices.contains(FE.getSource())) {
			double d;
			i = newPrices.indexOf(FE.getSource());

			try {
				d = Double.valueOf(newPrices.get(i).getText());
				newPrices.get(i).setText("" + d);
			} catch (NumberFormatException NE) {
				if (newPrices.get(i).getToolTipText().length() > 0) {
					d = 1;
					newPrices.get(i).setText(newPrices.get(i).getToolTipText());
				} else {
					d = 0;
					newPrices.get(i).setText("0");
				}
			}
			if (d < 0)
				newPrices.get(i).setText("" + (d * -1));
			if (newPrices.get(i).getText().length() > 0
					&& newQuans.get(i).getText().length() > 0
					&& addUnits.get(i).getSelectedIndex() > 0
					&& addProd.get(i).getSelectedIndex() > 0) {
				try {
					cost = getProductCost(addUnits.get(i).getSelectedItem()
							.toString(), addProd.get(i).getSelectedItem()
							.toString());
				} catch (SQLException SE) {
					error = "*Error: Price not found";
					cost = 0;
				}
				try {
					cost *= Double.valueOf(newQuans.get(i).getText());
				} catch (NumberFormatException e) {
					error = "*Error: Input must be a valid number";
				}
				newPrices.get(i).setText("" + cost); // get the cost of the sale
				totalBox.setText("" + calculateNewInvoiceCost()); // Update the
																	// total
			}
		} else if (FE.getSource() == inNumBox) {
			int Rnum = 0;
			try {
				Rnum = Integer.valueOf(inNumBox.getText());
			} catch (NumberFormatException NE) {
				Rnum = Integer.valueOf(Invoices.get(Invoices.size() - 1)
						.getReceiptNum()) + 1;
				inNumBox.setText("" + Rnum);
				error = "*Error: Enter a valid number for Receipt no.";
				inNumBox.requestFocus();
			}

			if (Rnum < 0) {
				Rnum *= -1;
				inNumBox.setText("" + Rnum);
				error = "*Error: Enter positive numbers only";
			}

		} else if (FE.getSource() == limitBox) {
			double d = 0;

			try {
				d = Double.valueOf(limitBox.getText());
				if (d < 0)
					d *= -1;
			} catch (NumberFormatException NE) {
				d = 0;

			}
			limitBox.setText("" + d);
			changeDebtPane(d);
			paintAncestors(debtPane);
		}
	}

	@Override
	public void keyPressed(KeyEvent KE) {
		// TODO Auto-generated method stub

	}

	@Override
	public void keyReleased(KeyEvent KE) {
		int i;
		error = "";
		 
		if (KE.getSource() == customerName
				&& KE.getKeyCode() == KeyEvent.VK_ENTER)
			totalBox.requestFocus();
		else if (KE.getSource() == totalBox
				&& KE.getKeyCode() == KeyEvent.VK_ENTER)
			balanceBox.requestFocus();
		else if (KE.getSource() == balanceBox
				&& KE.getKeyCode() == KeyEvent.VK_ENTER)
			customerName.requestFocus();
		else if (KE.getSource() == soldToBox) {
			if (KE.getKeyCode() == KeyEvent.VK_ENTER)
				inNumBox.requestFocus();

			if (newQuans.size() > 1)
				insert.setEnabled(true);
		} else if (KE.getSource() == inNumBox) {
			if (KE.getKeyCode() == KeyEvent.VK_ENTER)
				balanceBox.requestFocus();

			if (inNumBox.getText().length() == 0)
				insert.setEnabled(false);
			else if (newQuans.size() >1)
				insert.setEnabled(true);
		} else if (KE.getSource() == balanceBox
				&& KE.getKeyCode() == KeyEvent.VK_ENTER)
			soldToBox.requestFocus();
		else if (quantityBoxes != null
				&& quantityBoxes.contains(KE.getSource())) {
			i = quantityBoxes.indexOf(KE.getSource());
			if (KE.getKeyCode() == KeyEvent.VK_ENTER)
				priceBoxes.get(i).requestFocus();
			else if (quantityBoxes.get(i).isEditable()
					&& KE.getKeyCode() == KeyEvent.VK_DELETE
					&& priceBoxes.size() > 1)
				deleteSale(i, quantityBoxes.get(i));
		} else if (priceBoxes != null && priceBoxes.contains(KE.getSource())) {
			i = priceBoxes.indexOf(KE.getSource());

			if (KE.getKeyCode() == KeyEvent.VK_ENTER
					&& i < priceBoxes.size() - 1)
				quantityBoxes.get(i + 1).requestFocus();
			else if (priceBoxes.get(i).isEditable()
					&& KE.getKeyCode() == KeyEvent.VK_DELETE
					&& priceBoxes.size() > 1)
				deleteSale(i, quantityBoxes.get(i));
		} else if (newQuans.contains(KE.getSource())) {
			i = newQuans.indexOf(KE.getSource());
			if (KE.getKeyCode() == KeyEvent.VK_ENTER)
				newPrices.get(i).requestFocus();
			else if (i < newQuans.size() - 1
					&& KE.getKeyCode() == KeyEvent.VK_DELETE)
				deleteSale(i, newQuans.get(i));
		} else if (newPrices.contains(KE.getSource())) {
			i = newPrices.indexOf(KE.getSource());
			if (KE.getKeyCode() == KeyEvent.VK_ENTER
					&& i < newPrices.size() - 1)
				newQuans.get(i + 1).requestFocus();
		}

		else if (KE.getSource() == limitBox
				&& KE.getKeyCode() == KeyEvent.VK_ENTER) {
			int n = 0;
			try {
				n = Integer.parseInt(limitBox.getText());
				changeDebtPane(n);
			} catch (Exception e) {
				error = "*Error: Please enter a valid number";
			}
		}

	}

	@Override
	public void keyTyped(KeyEvent KE) {
		// TODO Auto-generated method stub

	}

}
